package com.cloud.weixin.project.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloud.common.core.asserts.ApiAssert;
import com.cloud.common.core.enums.ErrorCodeEnum;
import com.cloud.weixin.project.mapper.WxTemplateMapper;
import com.cloud.weixin.project.model.entity.WxTemplate;
import com.cloud.weixin.project.service.IWxTemplateService;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 微信模板 服务实现类
 * </p>
 *
 * @author Sam
 * @since 2021-04-27
 */
@Service
public class WxTemplateServiceImpl extends ServiceImpl<WxTemplateMapper, WxTemplate> implements IWxTemplateService {

    @Autowired
    private WxMpService wxMpService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void sync() {
        List<WxMpTemplate> mpTemplateList = null;
        try {
            mpTemplateList = wxMpService.getTemplateMsgService().getAllPrivateTemplate();
        } catch (WxErrorException e) {
            ApiAssert.failure(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("同步微信模板失败"), e);
        }
        List<WxTemplate> templateList = new ArrayList<>();
        mpTemplateList.forEach(temp -> templateList.add(JSONObject.parseObject(temp.toString(), WxTemplate.class)));
        this.remove(Wrappers.emptyWrapper());
        this.saveBatch(templateList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delWxTemplate(String id) {
        WxTemplate template = this.getById(id);
        ApiAssert.notNull(ErrorCodeEnum.BAD_SELECT_FAILURE, template);
        try {
            wxMpService.getTemplateMsgService().delPrivateTemplate(template.getTemplateId());
        } catch (WxErrorException e) {
            ApiAssert.failure(ErrorCodeEnum.BAD_DELETE_FAILURE, e);
        }
        ApiAssert.isTrue(ErrorCodeEnum.BAD_DELETE_FAILURE, this.removeById(id));
    }

    @Override
    public String sendWxTempMsg(String openId, String templateId, String url, Map<String, String> map) {
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .templateId(templateId)
                .url(url)
                .build();
        map.forEach((k, v) -> {
            templateMessage.addData(new WxMpTemplateData(k, v, "#000000"));
        });
        String msgId = null;
        try {
            msgId = wxMpService.getTemplateMsgService().sendTemplateMsg(templateMessage);
        } catch (WxErrorException e) {
            log.error("推送失败！", e);
        }
        return msgId;
    }
}
